package com.hra.usbtest;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.w(TAG, "onReceive: " + action);
            Log.w(TAG, "onReceive: intent = " + intent);
            Log.w(TAG, "onReceive: getData = " + intent.getData());
            switch (action) {
                case UsbManager.ACTION_USB_DEVICE_ATTACHED:
                    Log.w(TAG, "onReceive: ATTACHED_DEVICE = " + intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
                    if (statusText != null) {
                        statusText.setText("U盘已插入");
                        updateStatus();
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED:
                    usbRootUri = null;
                    if (statusText != null) {
                        statusText.setText("U盘已拔出");
                        writeButton.setEnabled(false);
                        deleteButton.setEnabled(false);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private TextView statusText;
    private Button writeButton;
    private Button deleteButton;
    private Uri usbRootUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        statusText = findViewById(R.id.status_text);
        writeButton = findViewById(R.id.write_button);
        deleteButton = findViewById(R.id.delete_button);

        // 初始化USB接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(usbReceiver, filter);

        writeButton.setOnClickListener(v -> {
            if (usbRootUri != null) {
                writeButton.setEnabled(false);
                deleteButton.setEnabled(false);
                statusText.setText("开始写入文件到U盘");
                Log.w(TAG, "OnClick: 开始写入文件到U盘");
                copyFileToUSB();
            } else {
                updateStatus();
            }
        });

        deleteButton.setOnClickListener(v -> {
            writeButton.setEnabled(false);
            deleteButton.setEnabled(false);
            deleteFileFromUSB();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (usbRootUri != null) {
            statusText.setText("检测到U盘");
        } else {
            // 请求用户选择U盘文件夹
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, 1001);
        }
        updateStatus();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            usbRootUri = data.getData();
            Log.w(TAG, "onActivityResult: usbRootUri = " + usbRootUri);
            // 获取持久写入权限
            getContentResolver().takePersistableUriPermission(
                    usbRootUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            );
        }
    }

    private void updateStatus() {
        if (usbRootUri != null) {
            writeButton.setEnabled(true);
            deleteButton.setEnabled(true);
        } else {
            Toast.makeText(this, "请先选择U盘目录", Toast.LENGTH_SHORT).show();
            statusText.setText("请先选择U盘目录");
            writeButton.setEnabled(false);
            deleteButton.setEnabled(false);
        }
    }

    private void copyFileToUSB() {
        new Thread(() -> {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = getAssets().open("test.txt");

                DocumentFile root = DocumentFile.fromTreeUri(this, usbRootUri);
                DocumentFile existingFile = root.findFile("test.txt");
                if (existingFile != null) {
                    existingFile.delete();
                }
                DocumentFile newFile = root.createFile("text/plain", "test");

                Log.w(TAG, "copyFileToUSB: 正在向U盘写入文件...");
                runOnUiThread(() -> statusText.setText("正在向U盘写入文件..."));
                out = getContentResolver().openOutputStream(newFile.getUri());
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }

                out.flush();
                runOnUiThread(() -> statusText.setText("文件写入成功!"));
            } catch (Exception e) {
                Log.e(TAG, "copyFileToUSB: Exception = " + e);
                e.printStackTrace();
                runOnUiThread(() -> statusText.setText("文件写入失败: " + e.getMessage()));
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            runOnUiThread(this::updateStatus);
        }).start();
    }

    private void deleteFileFromUSB() {
        new Thread(() -> {
            try {
                DocumentFile root = DocumentFile.fromTreeUri(this, usbRootUri);
                Log.w(TAG, "deleteFileFromUSB: root = " + root);
                if (root == null) {
                    return;
                }
                for (DocumentFile file : root.listFiles()) {
                    Log.w(TAG, "deleteFileFromUSB: file.getName() = " + file.getName());
                    if ("test.txt".equals(file.getName())) {
                        boolean deleted = file.delete();
                        runOnUiThread(() -> {
                            if (deleted) {
                                statusText.setText("写入的文件成功删除");
                                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                            } else {
                                statusText.setText("删除失败");
                            }
                        });
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            runOnUiThread(this::updateStatus);
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbReceiver);
    }
}
